// app/controller/collection_record_controller.js
'use strict';

const Controller = require('egg').Controller;

class CollectionRecordController extends Controller {
  // 获取催款记录列表
  async index() {
    const { ctx } = this;
    const { page = 1, limit = 20, customerName, collectionMethod, collectionResult, startDate, endDate } = ctx.query;
    
    try {
      // 构建查询条件
      const where = {};
      
      // 添加组织过滤条件
      if (ctx.state.organizationId) {
        where.organizationId = ctx.state.organizationId;
      }
      
      if (collectionMethod) {
        where.collectionMethod = collectionMethod;
      }
      
      if (collectionResult) {
        where.responseResult = collectionResult;
      }
      
      if (startDate || endDate) {
        where.collectionDate = {};
        if (startDate) {
          where.collectionDate[ctx.app.Sequelize.Op.gte] = new Date(startDate);
        }
        if (endDate) {
          where.collectionDate[ctx.app.Sequelize.Op.lte] = new Date(endDate);
        }
      }

      // 如果有客户名称查询条件，需要先查询客户ID
      let customerId = null;
      if (customerName) {
        const customer = await ctx.model.CustomerModel.findOne({
          where: {
            name: {
              [ctx.app.Sequelize.Op.like]: `%${customerName}%`
            }
          }
        });
        
        if (customer) {
          customerId = customer.id;
        } else {
          // 如果没找到客户，返回空结果
          ctx.page([], 0, parseInt(page), parseInt(limit));
          return;
        }
      }

      // 分页查询
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 构建包含销售订单和客户的查询
      const queryOptions = {
        where,
        order: [['collection_date', 'DESC']],
        limit: parseInt(limit),
        offset,
        include: [{
          model: ctx.model.SalesOrderModel,
          as: 'order',
          include: [{
            model: ctx.model.CustomerModel,
          as: 'customer',
            attributes: ['name']
          }],
          attributes: ['id', 'order_no', 'order_amount', 'order_date']
        }]
      };
      
      // 如果有客户ID条件，添加到销售订单查询条件中
      if (customerId) {
        // 使用Sequelize的Op.and操作符确保不覆盖原有的include条件
        const { Op } = ctx.app.Sequelize;
        queryOptions.include[0].where = {
          [Op.and]: [
            queryOptions.include[0].where || {},
            { customerId: customerId }
          ]
        };
      }

      const { rows, count } = await ctx.model.CollectionRecordModel.findAndCountAll(queryOptions);

      // 转换数据格式以匹配前端期望的结构
      const formattedRecords = rows.map(record => {
        const order = record.order;
        const customer = order ? order.customer : null;
        
        return {
          orderInfo: {
            platformOrderId: order ? order.orderNo : '',
            amount: order ? order.orderAmount : 0,
            orderDate: order ? order.orderDate : ''
          },
          customerInfo: {
            name: customer ? customer.name : '',
            contactPerson: record.contactPerson || '',
            phone: '', // 销售订单模型中没有电话字段
            email: ''  // 销售订单模型中没有邮箱字段
          },
          collectionInfo: {
            collectionId: `COL${String(record.id).padStart(6, '0')}`,
            method: record.collectionMethod,
            duration: 0, // 数据库中没有时长字段，需要计算或添加
            result: record.responseResult,
            collectionTime: record.collectionDate,
            operator: record.createdBy.toString(), // 操作人ID转为字符串
            notes: record.responseResult || '',
            isBatch: false, // 暂时设置为false
            nextFollowupDate: record.nextFollowupDate,
            satisfactionScore: 0 // 暂时设置为0
          }
        };
      });

      ctx.page(formattedRecords, count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取催款记录列表失败:', error);
      ctx.error(`获取催款记录列表失败: ${error.message}`);
    }
  }
  
  // 根据销售订单ID获取催款记录列表 - 新增方法
  async getRecordsByOrder() {
    const { ctx } = this;
    const { orderId } = ctx.query;
    
    try {
      if (!orderId) {
        ctx.error('订单ID不能为空', 400);
        return;
      }
      
      const records = await ctx.service.collectionRecordService.getRecordsByOrderId(orderId);
      
      ctx.success(records);
    } catch (error) {
      ctx.logger.error('根据订单ID获取催款记录列表失败:', error);
      ctx.error('获取催款记录列表失败');
    }
  }
  
  // 获取催款记录详情
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const record = await ctx.service.collectionRecordService.getRecordById(id);
      
      if (!record) {
        ctx.error('催款记录不存在', 404);
        return;
      }
      
      ctx.success(record);
    } catch (error) {
      ctx.logger.error('获取催款记录详情失败:', error);
      ctx.error('获取催款记录详情失败');
    }
  }
  
  // 创建催款记录
  async create() {
    const { ctx } = this;
    const recordData = ctx.request.body;
    
    try {
      // 设置组织ID
      if (ctx.state.organizationId) {
        recordData.organizationId = ctx.state.organizationId;
      } else {
        recordData.organizationId = 1; // 默认组织ID
      }
      
      // 验证数据
      if (!recordData.salesOrderId) {
        ctx.error('销售订单ID不能为空', 400);
        return;
      }
      
      if (!recordData.collectionDate) {
        ctx.error('催款日期不能为空', 400);
        return;
      }
      
      const result = await ctx.service.collectionRecordService.createRecord(recordData);
      
      ctx.success(result, '催款记录创建成功');
    } catch (error) {
      ctx.logger.error('创建催款记录失败:', error);
      ctx.error(`创建催款记录失败: ${error.message}`);
    }
  }
  
  // 更新催款记录
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const recordData = ctx.request.body;
    
    try {
      const record = await ctx.service.collectionRecordService.getRecordById(id);
      
      if (!record) {
        ctx.error('催款记录不存在', 404);
        return;
      }
      
      const result = await ctx.service.collectionRecordService.updateRecord(id, recordData);
      ctx.success(result, '催款记录更新成功');
    } catch (error) {
      ctx.logger.error('更新催款记录失败:', error);
      ctx.error('更新催款记录失败');
    }
  }
  
  // 删除催款记录
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const record = await ctx.service.collectionRecordService.getRecordById(id);
      
      if (!record) {
        ctx.error('催款记录不存在', 404);
        return;
      }
      
      await ctx.service.collectionRecordService.deleteRecord(id);
      ctx.success(null, '催款记录删除成功');
    } catch (error) {
      ctx.logger.error('删除催款记录失败:', error);
      ctx.error('删除催款记录失败');
    }
  }
}

module.exports = CollectionRecordController;